package com.shop.cart.service.impl;

import com.netflix.discovery.converters.Auto;
import com.shop.cart.entity.CartItem;
import com.shop.cart.entity.CartItemVO;
import com.shop.cart.mapper.ProductMapper;
import com.shop.cart.service.CartService;
import com.shop.common.constant.RedisConstant;
import com.shop.common.entity.CommonResult;
import com.shop.common.pojo.Product;
import com.shop.common.util.StrUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.*;

/**
 * @author ghy
 * @version 1.0
 * @date 2020-11-03
 */
@Service
public class CartServiceImpl implements CartService {

    @Autowired
    RedisTemplate redisTemplate;

    /**
     * 加入商品到购物车
     * 可以增加和减少
     *
     * @param pid
     * @param num
     * @param cookieCartToken
     * @return
     */
    @Override
    public CommonResult add(Long pid, Integer num, String token) {
        if(pid < 0) {
            throw new RuntimeException("购买的商品不存在");
        }

        //1.获取购物车
        String cartKey = StrUtils.getRedisKey(RedisConstant.CART_TOKEN, token);
        List<CartItem> list = (List<CartItem>) redisTemplate.opsForValue().get(cartKey);

        //1.判断是否存在购物车?
        if (list == null || list.size() == 0) {
            //不存在
            if(num < 0) {
                throw new RuntimeException("没有购物车，加入商品数量必须是正数");
            }

            //创建购物项
            CartItem cartItem = new CartItem(pid, num, new Date());
            //创建购物车
            list = new ArrayList<>();
            //把购物项增加到购物车中
            list.add(cartItem);
            //把购物车增加redis中
            redisTemplate.opsForValue().set(cartKey, list);
            return new CommonResult("加入购物车成功:" +token,list);
        }


        //存在
        for (CartItem cartItem : list) {
            //判断购物车中是否有该商品对应的购物项?
            if (cartItem.getPid().longValue() == pid.longValue()) {
                //有
                //增加该商品对应的购物项的数量，更新时间
                Integer oldNum = cartItem.getNum();
                //更新购物车商品的数量
                cartItem.setNum(oldNum + num);
                //更新时间
                cartItem.setUpdateTime(new Date());
                if(cartItem.getNum() <= 0) {
                    //如果当前购物项的数量已经小于等于0了，那么该购物项应该从购物车中移除
                    list.remove(cartItem);
                }
                //把购物车增加redis中
                redisTemplate.opsForValue().set(cartKey, list);
                return new CommonResult("加入购物车成功:" + token,list);
            }
        }

        //没有
        //创建购物项
        CartItem cartItem = new CartItem(pid, num, new Date());
        //把购物项增加到购物车中
        list.add(cartItem);
        //把购物车增加redis中
        redisTemplate.opsForValue().set(cartKey, list);
        return new CommonResult("加入购物车成功" + token,list);
    }

    @Autowired
    private ProductMapper productMapper;

    /**
     * 展示购物车
     *
     * @param token
     */
    @Override
    public List<CartItemVO> show(String token) {
        //1.根据购物车的cookie组装一个redisKey
        String redis_cart_token = StrUtils.getRedisKey(RedisConstant.CART_TOKEN, token);
        //2.获取redis中的购物车
        List<CartItem> list = (List<CartItem>)redisTemplate.opsForValue().get(redis_cart_token);
        //3.页面展示购物车数据
        List<CartItemVO> cart = new ArrayList<>();
        //4.把redis中购物车封装成页面展示的购物车数据
        if(list != null && list.size() > 0) {
            for (CartItem cartItem : list) {
                Long pid = cartItem.getPid();
                //根据ID查询商品数据
                Product product = productMapper.findById(pid);
                //-----
                CartItemVO vo = new CartItemVO(product, cartItem.getNum(), cartItem.getUpdateTime());
                cart.add(vo);
            }
        }

        /*Comparator<CartItemVO> comparator = new Comparator<CartItemVO>() {

            @Override
            public int compare(CartItemVO o1, CartItemVO o2) {
                return (int)(o1.getUpdateTime().getTime() - o2.getUpdateTime().getTime());
            }
        };*/

        //排序，使用lomdba表达式
        Collections.sort(cart, (o1,o2) -> (int)(o2.getUpdateTime().getTime() - o1.getUpdateTime().getTime()));

        return cart;//[]
    }

    @Autowired
    RestTemplate restTemplate;

    /**
     * 根据login_token得到用户ID
     *
     * @return
     */
    @Override
    public String getUserId(String token) {
        //对接登录模块获取用户名的接口
        //获取这个 http://localhost:8001/login/name 的返回值
        //return loginFeign.name(token);
        //String url = "http://localhost:8001/login/name";
        String url = "http://shop-user-service/login/name";
        //设置请求头，cookie头
        HttpHeaders headers = new HttpHeaders();

        List<String> list = new ArrayList<>();
        list.add("login_token=" + token);

        headers.put(HttpHeaders.COOKIE, list);

        HttpEntity request = new HttpEntity(headers);
        //返回用户信息
        /**
         * {
         *     "id":20
         *     "name":"zhangsan"
         *     "phone":"13526541255",
         *     "email":null
         * }
         */
        CommonResult result = restTemplate.postForObject(url, request, CommonResult.class);
        Map data = (Map) result.getData();
        //返回用户ID
        return (String) data.get("id");
    }
}
